/*
 * @lc app=leetcode.cn id=652 lang=typescript
 *
 * [652] 寻找重复的子树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> {
  // 序列化字符串到结点的映射
  const nodes = new Map<string, TreeNode>();
  // 保存重复的结点
  const repeatNode = new Set<TreeNode>();
  // 递归序列化二叉树
  // x(左子树序列化结果)(右子树序列化结果)
  const dfs = (node: TreeNode | null): string => {
    if (!node) return '';
    let substr = '';
    substr += node.val;
    substr += '(';
    substr += dfs(node.left);
    substr += ')(';
    substr += dfs(node.right);
    substr += ')';

    if (nodes.has(substr)) {
      repeatNode.add(nodes.get(substr));
    } else {
      nodes.set(substr, node);
    }

    return substr;
  };
  dfs(root);
  return [...repeatNode];
}
// @lc code=end
